using Microsoft.Extensions.DependencyInjection;
using Services;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using WorkPieceDataCapture.ViewModels;
using WorkPieceDataCapture.Views;
using Microsoft.Extensions.Configuration;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Linq;
using System;

namespace ViewModels
{
    public class vm_MainWindow : vm_Base
    {
        WorkPieceDataCaptureRespository respository;
        public ICommand MenuSelectCommand { get; set; }
        private uc_WorkPieceDataCapture_RealTime? _realtime;
        private uc_WorkPieceDataCapture_Search? _search;
        private uc_Search_PointCheck? _searchPointCheck;
        private uc_Chart_NG? _chartNG;
        private uc_Chart_Range? _ChartRange;
        private UserControl _uc;
        public UserControl? uc
        {
            get { return _uc; }
            set
            {
                _uc = value;
                OnPropertyChanged("uc");
            }
        }

        private readonly IConfiguration _configuration;
        private bool _isExiting = false;

        public vm_MainWindow(IServiceProvider serviceProvider, MQTT_Client mqttclient, IConfiguration configuration)
        {
            this.respository = new WorkPieceDataCaptureRespository(serviceProvider);
            this._configuration = configuration;
            // 在应用退出时标记退出，优雅结束后台循环
            if (Application.Current != null)
            {
                Application.Current.Exit += (_, __) => { _isExiting = true; };
            }
            #region 连接MQTT
            mqttclient.topicsNeedSubscribe = new List<string>() { "BM21生产数据", "BM21点检数据" };
            var result = mqttclient.ConnectToServer();
            if (!result.bSuccess)
            {
                MessageBox.Show("MQTT未连接，请检查位于" + mqttclient.model_login.strIPAddress + ":" + mqttclient.model_login.intPort.ToString() + "的MQTT服务是否已开启");
                Application.Current.Shutdown();
            }
            #endregion
            #region 子界面注册
            //实时生产数据采集界面
            _realtime = new uc_WorkPieceDataCapture_RealTime();
            var vm_realtime = serviceProvider.GetService<vm_WorkPieceDatacapture_RealTime>();
            if (vm_realtime != null)
            {
                _realtime.DataContext = vm_realtime;
            }
            //历史数据查询界面
            _search = new uc_WorkPieceDataCapture_Search();
            var vm_search = serviceProvider.GetService<vm_WorkPieceDatacapture_Search>();
            if (vm_search != null)
            {
                _search.DataContext = vm_search;
            }
            //点检记录查询界面
            _searchPointCheck = new uc_Search_PointCheck();
            var vm_searchPointCheck = serviceProvider.GetService<vm_Search_PointCheck>();
            if (vm_searchPointCheck != null)
            {
                _searchPointCheck.DataContext = vm_searchPointCheck;
            }
            //NG饼状图界面
            _chartNG = new uc_Chart_NG();
            var vm_Chart_NG = serviceProvider.GetService<vm_Chart_NG>();
            if (vm_Chart_NG != null)
            {
                _chartNG.DataContext = vm_Chart_NG;
            }
            //柱状图界面
            _ChartRange = new uc_Chart_Range();
            var vm_chartRange = serviceProvider.GetService<vm_Chart_Range>();
            if (vm_chartRange != null)
            {
                _ChartRange.DataContext = vm_chartRange;
            }
            #endregion
            #region 事件注册
            this.MenuSelectCommand = new RelayCommand(MenuSelected);
            #endregion
            _ = DataArchive();
            _ = MonitorKaoQinMonitorAsync();
        }
        //菜单按钮选择事件处理
        private void MenuSelected(object parameter)
        {
            string strButtonName = parameter as string;
            switch (strButtonName)
            {
                case "实时数据采集":
                    this.uc = _realtime;
                    break;
                case "历史数据查询":
                    this.uc = _search;
                    break;
                case "NG占比分析":
                    this.uc = _chartNG;
                    break;
                case "NG数量分布":
                    this.uc = _ChartRange;
                    break;
                case "点检记录查询":
                    this.uc = _searchPointCheck;
                    break;
            }
        }
        private async Task DataArchive()
        {
            while (!_isExiting)
            {
                var result = await this.respository.DataArchivingAsync();
                await Task.Delay(new TimeSpan(0, 0, 10));
            }
        }

        private async Task MonitorKaoQinMonitorAsync()
        {
            // 默认间隔（秒），异常情况下也能继续执行
            int defaultIntervalSeconds = 30;
            while (!_isExiting)
            {
                int intervalSeconds = defaultIntervalSeconds;
                try
                {
                    var section = _configuration.GetSection("KaoQinMonitor");
                    var autoEnsureStr = section["AutoEnsureRunning"]; 
                    bool autoEnsure = string.IsNullOrWhiteSpace(autoEnsureStr) ? true : (bool.TryParse(autoEnsureStr, out var b) ? b : true);
                    string exeFolder = section["ExecutableFolder"] ?? string.Empty;
                    string exeName = section["ExeName"] ?? "KaoQinMonitor.exe";
                    string startArgs = section["StartArgs"] ?? string.Empty;
                    var intervalStr = section["CheckIntervalSeconds"];
                    intervalSeconds = (int.TryParse(intervalStr, out var parsed) && parsed > 0) ? parsed : defaultIntervalSeconds;

                    if (autoEnsure)
                    {
                        string processName = Path.GetFileNameWithoutExtension(exeName);
                        bool isRunning = false;
                        try
                        {
                            isRunning = Process.GetProcessesByName(processName).Any();
                        }
                        catch { /* ignore */ }

                        if (!isRunning)
                        {
                            if (!string.IsNullOrWhiteSpace(exeFolder))
                            {
                                string exePath = Path.Combine(exeFolder, exeName);
                                if (File.Exists(exePath))
                                {
                                    try
                                    {
                                        var psi = new ProcessStartInfo
                                        {
                                            FileName = exePath,
                                            WorkingDirectory = exeFolder,
                                            UseShellExecute = true,
                                            Arguments = startArgs
                                        };
                                        Process.Start(psi);
                                    }
                                    catch (Exception)
                                    {
                                        // 可在此集成日志，如果需要
                                    }
                                }
                                else
                                {
                                    // 可在此记录：配置的路径不存在
                                }
                            }
                            else
                            {
                                // 可在此记录：未配置可执行文件目录
                            }
                        }
                    }
                }
                catch
                {
                    // 忽略单次异常，继续循环
                }
                await Task.Delay(TimeSpan.FromSeconds(intervalSeconds));
            }
        }
    }
}
